#include "shmem.h"
char *shm_get_data()
{
    struct shm_param shm;
    struct std_node *node = NULL;
    shm = shm_creat(&nodenum);

    /* 从共享内存中拿到设备数据点data */
    int *head = (int *)shm_getaddr(&shm);
    node = (struct std_node *)(head + 1);
    // 序列化生成json
    cJSON *root = cJSON_CreateObject();
    cJSON *data = cJSON_CreateArray();
    
    cJSON *key = cJSON_CreateObject();
    cJSON *value = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "data", data);
    // printf("%d\n", nodenum);

    for (int i = 0; i < nodenum; i++)
    {
        cJSON *item = cJSON_CreateObject();
        key = cJSON_CreateNumber(node->key);
        switch (node->type)
        {
        case 1:
            value = cJSON_CreateNumber(node->new_val.b_val); //bool
            break;
        case 2:
            value = cJSON_CreateNumber(node->new_val.i_val); //int
            break;
        case 3:
            value = cJSON_CreateNumber(node->new_val.f_val); //float
            break;
        default:
            break;
        }
        cJSON_AddItemToObject(item, "key", key);
        cJSON_AddItemToObject(item, "value", value);
        cJSON_AddItemToArray(data, item);
        node++;
    }
    // printf("------------\n");
    char *p = cJSON_Print(root);
    // printf("%s\n", p);
    return p;
}